package yxy.apple.util;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Base64Utility {
	public static byte[] decode(byte base64[]) {
		return Base64.getDecoder().decode(base64);
	}

	public static String decodeToUTF8String(String base64) {
		return Base64Utility.decodeToString(base64, "UTF-8");
	}

	public static String decodeToUTF8String(byte base64[]) {
		return Base64Utility.decodeToString(base64, "UTF-8");
	}

	public static String decodeToString(byte base64[], String encoding) {
		return Base64Utility.decodeToString(base64, encoding, null);
	}

	public static String decodeToString(String base64, String encoding) {
		return Base64Utility.decodeToString(base64.getBytes(), encoding, null);
	}

	public static String decodeToString(byte base64[], String encoding, String defaultString) {
		byte[] decoded = Base64Utility.decode(base64);
		if (decoded != null) {
			try {
				return new String(decoded, encoding);
			} catch (UnsupportedEncodingException e) {
				return defaultString;
			}
		} else {
			return defaultString;
		}
	}

	public static String encodeToString(String raw) {
		return Base64Utility.encodeToString(raw.getBytes());
	}

	public static String encodeToString(byte[] raw) {
		return Base64.getEncoder().encodeToString(raw);
	}

	public static byte[] encode(byte[] raw) {
		return Base64.getEncoder().encode(raw);
	}

}
